from sqlalchemy.orm import Session
from schema import Plot_Crop_schema
from model import Plot_Crop_model



def get_Plot_Crop(db: Session, ID: int):
    return db.query(Plot_Crop_model.Plot_crop).filter(Plot_Crop_model.Plot_crop.ID == ID).first()


def get_all_Plot_Crop(db: Session):
    return db.query(Plot_Crop_model.Plot_crop).all()


def delete_Plot_Crop(db: Session, ID):
    to_delete = db.query(Plot_Crop_model.Plot_crop).filter(Plot_Crop_model.Plot_crop.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Plot_Crop(db: Session, Plot_Crop: Plot_Crop_schema.Plot_crop):
    db_Plot_Crop = Plot_Crop_model.Plot_crop(
        CropName=Plot_Crop.CropName,
        PlantingStartDate=Plot_Crop.PlantingStartDate,
        PlantingEndDate=Plot_Crop.PlantingEndDate,
        CropPropertiesJSON=Plot_Crop.CropPropertiesJSON,
    )
    db.add(db_Plot_Crop)
    db.commit()
    db.refresh(db_Plot_Crop)
    return db_Plot_Crop


def update_Plot_Crop(db: Session, ID, field_name, new_value):
    db_Plot_Crop = db.query(Plot_Crop_model.Plot_crop).filter(Plot_Crop_model.Plot_crop.ID == ID).first()
    setattr(db_Plot_Crop, field_name, new_value)
    db.commit()
    db.refresh(db_Plot_Crop)
    return db_Plot_Crop
